package org.benjamin.lending.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.benjamin.lending.domain.entity.MemberInfo;
import org.benjamin.lending.repository.MemberInfoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

public class CountAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
	
	@Autowired
	private MemberInfoRepository memberInfoRepository;

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws ServletException, IOException {
		UserDetails userDetails = (UserDetails)authentication.getPrincipal();
		
		MemberInfo memberInfo = this.memberInfoRepository.findByUsername(userDetails.getUsername());
		if(memberInfo == null) {
			logger.info("网贷系统未能查询到用户对象，现在试图创建数据同步数据");
			memberInfo = new MemberInfo();
			memberInfo.setUsername(userDetails.getUsername());
			this.memberInfoRepository.save(memberInfo);
		}
		super.onAuthenticationSuccess(request, response, authentication);
	}
	
	

}
